package org.example.multiThreading.Lock;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestTicket {
    public static void main(String[] args) {
        //创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 7, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3));
        for (int i = 0; i < 4; i++) {
            //创建Ticket对象
            Ticket ticket = new Ticket();
            //提交线程执行
            executor.execute(ticket);
        }
        //关闭线程池
        executor.shutdown();
    }
}

class Ticket implements Runnable{

    static int ticket = 100;
    //创建Lock锁
    static Lock lock=new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //获取锁
            lock.lock();
            try {
                if(ticket>0){
                    System.out.println(Thread.currentThread().getName()+"卖出了一张票，还剩"+(--ticket)+"张。");
                }else{
                    break;
                }
            }finally {
                //释放锁
                lock.unlock();
            }
        }
    }
}
